package dayu.realm;

import dayu.pojo.User;
import dayu.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author dayu
 * @create 2018/12/14 14:45
 * @Description
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("UserRealm.doGetAuthorizationInfo");
        //认证方法返回的第一个对象，要注意object的类型
        String loginName = (String) principalCollection.getPrimaryPrincipal();

        Set<String> roles = userService.findRolesByLoginName(loginName);
        Set<String> permissions = userService.findPermissionsByLoginName(loginName);
        for (String role : roles) {
            System.out.println("role=="+role);
        }
        for (String permission : permissions) {
            System.out.println("==permission=="+permission);
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRoles(roles);
        info.addStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String loginName = (String) token.getPrincipal();
        System.out.println("UserRealm.doGetAuthenticationInfo");
        System.out.println("loginName="+loginName);

        User user = userService.findUserByLoginName(loginName);
        if (user == null) {
            System.out.println("==user null==");
            throw new UnknownAccountException();
        }

        String password = user.getPassword();
        System.out.println("password="+password);

//        Object principal, Object hashedCredentials, ByteSource credentialsSalt, String realmName
        return new SimpleAuthenticationInfo(
                loginName,//用户名
                user.getPassword(),//密码
                ByteSource.Util.bytes(user.getLoginName()),//盐
                getName()//realm名称
        );
    }
}
